/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.TX;

import entity.Outlet;
import entity.StakeholderFood;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Singleton;

import javax.ejb.Schedule;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Randall Chia
 */
@Singleton
public class SchedulerSB implements SchedulerSBRemote {

    @PersistenceContext
    EntityManager em;
    
    @EJB
    private StakeholderBillingSBRemote sbr;
    private boolean isBillingEnabled = false;
    @EJB
    public static OutletDataModelSBRemote outletDMSB;
    @EJB
    public static StakeholderDataModelSBRemote stakeholderDMSB;
    @EJB
    public static TCubeDataModelSBRemote tcubeDMSB;

    public void enableBilling() {
        System.out.println("SchedulerBean: billing cycle enabled. Billing process will execute at the scheduled time");
        isBillingEnabled = true;
    }

    public void disableBilling() {
        System.out.println("SchedulerBean: billing cycle disabled");
        isBillingEnabled = false;
    }

    //To bill on the 3rd of every month: (dayOfMonth="3", persistent=false)
    @Schedule(second = "*/30", minute = "*", hour = "*", persistent = false)
    public void doWork() {
        if (isBillingEnabled) {

            Calendar cal = Calendar.getInstance();
            Date currentDate = cal.getTime();

            cal.add(Calendar.MONTH, -1); //the previous billing date is on the previous month
            Date previousDate = cal.getTime();

            System.out.println("Billing task executed on date: " + new Date());
            sbr.billStakeholders(previousDate, currentDate);
            System.out.println("Billing task COMPLETE \n\n\n");

        }
    }

    //The analytics run is scheduled to run at 01:00:00 AM on Day 1 of every month
    @Schedule(second = "0", minute = "0", hour = "1", dayOfMonth = "1", persistent = false)
    public void doMonthlyAnalytics() {
        //Insert method call to do the analytics here
//        Query q1 = em.createQuery("SELECT c FROM TCubeDataModel c");
//        List<TCubeDataModel> tdms = q1.getResultList();
//        TCubeDataModel tdm = tdms.get(0);
        tcubeDMSB.updateDataModel();
        
        Query q1 = em.createQuery("SELECT c FROM StakeholderFood c");
        List<StakeholderFood> sfs = q1.getResultList();
        for(StakeholderFood sf:sfs){
            stakeholderDMSB.updateDataModel(sf.getName());
        }
        
        Query q2 = em.createQuery("SELECT c FROM Outlet c");
        List<Outlet> os = q2.getResultList();
        for(Outlet o:os){
            outletDMSB.updateDataModel(o.getId());
        }
    }
}
